import axios from 'axios'
import JSONbig from 'json-bigint'
import { Message } from 'element-ui'
import { getToken, setToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 50000,
  transformResponse: [
    function (data) {
      if (typeof data === 'string') {
        const JSONbigString = new JSONbig({storeAsString: true})
        return JSONbigString.parse(data)
      } else {
        return data
      }
    }
  ]
})
const whiteRequest = ['/service-uaa/uaa/v1/oauth/publicKey', '/service-uaa/oauth/token']
service.interceptors.request.use(
  config => {
    if (whiteRequest.indexOf(config.url.split(config.baseURL)[0].split('?')[0]) === -1) {
      config.headers['Authorization'] = getToken() == null ? '' : getToken()
    }
    if(localStorage.getItem('industry') !== null){
       config.headers['industry'] = localStorage.getItem('industry')
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  response => {
    if (response.headers.authorization) {
      setToken(response.headers.authorization)
    }
    const res = response.data
    if (!res.code || res.code === 100000 || res.code === 200) {
      return res
    }  else if (res.code === 100004) {
      Message.error(res.msg)
      localStorage.removeItem('mall-front-tenant-Token')
      window.location.href = `${location.href.split('/#/')[0]}/#/login?redirect=${window.location.hash.slice(1)}`
      return Promise.reject(new Error(res.msg || 'Error'))
    } else if (res.code === 100007) {
      Message.error(res.msg)
      localStorage.removeItem('mall-front-tenant-Token')
      window.location.href = `${location.href.split('/#/')[0]}/#/login?redirect=${window.location.hash.slice(1)}`
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      Message.error({ message: res.msg || '出现未知错误，请稍后再试'})
      return Promise.reject(new Error(res.msg || 'Error'))
    }
  },
  error => {
    if (error.response.status === 401) {
      localStorage.removeItem('mall-front-tenant-Token')
      console.log(location.href)
      console.log(location.href.split('/#/'))
      console.log(location.href.split('/#/')[0])
      window.location.href = location.href.split('/#/')[0] + '/#/login'
      // Message.error(error.response.data.msg)
      Message.error({
        message: error.response.data.msg || '出现错误，请稍后再试'
      })
    } else {
      console.log(error)
      // Message.error(error)
      Message.error({
        message: error || '出现错误，请稍后再试'
      })
      return Promise.reject(error)
    }
  }
)

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params, type = 'post', header = {}) {
  return new Promise((resolve, reject) => {
    service({
      method: type,
      url: url,
      data: params,
      headers: header
    }).then(res => {
        // if (res.data.code === 100000) {
        resolve(res.data)
        // } else {
        //   Message.error(res.data.msg)
        // }
      }).catch(err => {
        reject(err.msg)
      })
  })
}
/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params, type = 'get', header = {}) {
  return new Promise((resolve, reject) => {
    service({
      method: type,
      url: url,
      params,
      headers: header
    }).then(res => {
        // if (res.data.code === 100000) {
        resolve(res.data)
        // } else {
        //   Message.error(res.data.msg)
        // }
      }).catch(err => {
        reject(err.msg)
      })
  })
}
/**
 * upload方法，对应upload请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function upload(url, params) {
  return new Promise((resolve, reject) => {
    service({
      method: 'post',
      url: url,
      data: params,
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      transformRequest: [
        function(data) {
          const formData = new FormData()
          Object.keys(data).map(key => {
            formData.append(key, data[key])
          })
          return formData
        }
      ]
    }).then(res => {
        // if (res.data.code === 100000) {
        resolve(res.data)
        // } else {
        //   Message.error(res.data.msg)
        // }
      }).catch(err => {
        reject(err.msg)
      })
  })
}
/**
 * download方法，对应download请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @param {String} fileName [保存的文件名]
 */
export function download(url, params, fileName) {
  return new Promise((resolve, reject) => {
    service({
      method: 'post',
      url: url,
      data: params,
      responseType: 'blob',
      transformResponse: function(data) {
        return (data instanceof Blob && data.size > 0) ? data : undefined
      }
    }).then(res => {
      if (res.data == null) {
        reject(new Error('下载文件失败'))
      } else {
        const blobData = new Blob([res.data], { type: 'application/octet-stream' })
        const blobUrl = window.URL.createObjectURL(blobData)
        const linkDom = document.createElement('a')
        linkDom.style.display = 'none'
        linkDom.href = blobUrl
        linkDom.setAttribute('download', fileName)
        if (typeof linkDom.download === 'undefined') {
          linkDom.setAttribute('target', '_blank')
        }
        document.body.appendChild(linkDom)
        linkDom.click()
        document.body.removeChild(linkDom)
        window.URL.revokeObjectURL(blobData)
        resolve()
      }
    }).catch(err => {
      if (err instanceof Blob) {
        const reader = new FileReader()
        reader.onload = function() {
          const jsonObj = JSON.parse(reader.result)
          reject((jsonObj || {}).errorMessage || '下载文件失败')
        }
        reader.readAsText(err)
      } else {
        reject(err.msg)
      }
    })
  })
}
export default service
